package com.xinyue.game.gateway.local;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.xinyue.game.gateway.common.GameGatewayConfig;
import com.xinyue.game.gateway.rocketmq.RocketMQClientService;
import com.xinyue.game.gateway.server.utils.GameServerUtil;
import com.xinyue.game.message.GameGatewayMessageHeader;
import com.xinyue.game.message.GameLogicMessageHeader;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * 负责向网关后面的服务发送消息
 *
 * @author 王广帅
 * @since 2023/6/28 20:47
 **/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class DispatcherRequestHandler extends ChannelInboundHandlerAdapter {

    private static Logger logger = LoggerFactory.getLogger(DispatcherRequestHandler.class);
    @Autowired
    private RocketMQClientService rocketMQClientService;
    @Autowired
    private GameGatewayConfig gameGatewayConfig;
    @Autowired
    private UserChannelService userChannelService;


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            ByteBuf byteBuf = (ByteBuf) msg;
            // 先读取一下包头
            GameGatewayMessageHeader gameGatewayMessageHeader = new GameLogicMessageHeader();
            gameGatewayMessageHeader.readHeader(byteBuf);
            logger.debug("收到客户端消息：{}", gameGatewayMessageHeader);
            GameLogicMessageHeader gameLogicMessageHeader = this.getGameLogicMessageHeader(ctx, gameGatewayMessageHeader);
            int totalLen = gameLogicMessageHeader.getTotalSize();
            ByteBuf headerByteBuf = Unpooled.buffer(totalLen);
            gameLogicMessageHeader.writeHeader(headerByteBuf);

            // 将新的包头和客户端发送的剩下的数据转发给网关后面的服务
            ByteBuf newBuf = Unpooled.wrappedBuffer(headerByteBuf, byteBuf);
            String gameId = String.valueOf(gameGatewayMessageHeader.getGameId());
            String serviceId = String.valueOf(gameGatewayMessageHeader.getGameServiceId());
            String topic = rocketMQClientService.getTopic(gameId, serviceId);
            String tag = String.valueOf(gameGatewayMessageHeader.getLogicMessageId());
            String playerId = userChannelService.getPlayerId(ctx);
            // 使用playerId作为Key，保证同一个用户的消息都在同一个队列中
            rocketMQClientService.sendMsg(playerId, topic, tag, newBuf);
            logger.debug("转发客户端消息：{}", gameLogicMessageHeader);
            ReferenceCountUtil.release(byteBuf);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    private GameLogicMessageHeader getGameLogicMessageHeader(ChannelHandlerContext ctx, GameGatewayMessageHeader header) {
        GameLogicMessageHeader logicHeader = new GameLogicMessageHeader();
        String clientIp = GameServerUtil.getRemoteIP(ctx.channel());
        logicHeader.setClientIp(clientIp);
        logicHeader.setGatewayId(header.getGameId());
        logicHeader.setGameServiceId(header.getGameServiceId());
        logicHeader.setGatewayId(logicHeader.getGatewayId());
        logicHeader.setRequestTime(header.getRequestTime());
        logicHeader.setGameId(header.getGameId());
        logicHeader.setRequestId(header.getRequestId());
        logicHeader.setLogicMessageId(header.getLogicMessageId());
        return logicHeader;
    }
}
